﻿using AutoMapper;
using B.S.Filtration.Domain;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Write.Api.Application.Command.ProcessCommand;
using MediatR;
using SqlSugar;
using Yitter.IdGenerator;

namespace B.S.Filtration.Write.Api.Application.CommandHander.ProcessHandler
{
    public class AddCraftsmanshipCommandHandler : IRequestHandler<AddCraftsmanshipCommand, APIResult<object>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public AddCraftsmanshipCommandHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(AddCraftsmanshipCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.code = APIResultCode.success;
            result.msg = "工艺添加成功";

            var model = mapper.Map<Craftsmanship>(request);

            model.CraftsmanshipCode = YitIdHelper.NextId().ToString();
            // 使用 ExecuteReturnIdentityAsync 方法插入数据并返回自增主键
            int productionPlanningId = await db.Insertable(model).ExecuteReturnIdentityAsync();
            
            // 将主键添加到结果中
            result.data = new { productionPlanningId };

            return await Task.FromResult(result);
        }
    }
}
